Skip to main content

Check if Two Strings are Anagram (gfg)

Problem Description

Given two strings a and b consisting of lowercase characters, the task is to check whether the two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, act and tac are an anagram of each other. Strings a and b can only contain lowercase alphabets.

Examples

Example 1:

Input: a = "listen", b = "silent"
Output: YES
Explanation: The characters in both strings are the same.

Example 2:

Input: a = "hello", b = "billion"
Output: NO
Explanation: The characters in the strings are different.

Your Task

You don't need to read input or print anything. Your task is to complete the function isAnagram() which takes the strings a and b as inputs and returns a boolean indicating whether the two strings are an anagram of each other.

Expected Time Complexity: O(nlogn)O(n \log n) for sorting-based approach or O(n)O(n) for counting-based approach.

Expected Auxiliary Space: O(1)O(1) for constant extra space.

Constraints

  • 1 ≤ |a|, |b| ≤ 10^5

Problem Explanation

The problem is to check if two strings are anagram of each other, meaning both strings should have the same characters in any order.

Code Implementation

Written by @arunimad6yuq
class Solution:
def isAnagram(self, a: str, b: str) -> bool:
# If lengths are different, they cannot be anagrams
if len(a) != len(b):
return False

# Sort and compare
return sorted(a) == sorted(b)

# Example usage
if __name__ == "__main__":
solution = Solution()
print(solution.isAnagram("listen", "silent")) # Expected output: True
print(solution.isAnagram("hello", "billion")) # Expected output: False

Example Walkthrough

For the strings a = "listen" and b = "silent":

  1. Check the lengths of a and b. They are both 6.
  2. Sort both strings: a becomes eilnst and b becomes eilnst.
  3. Compare the sorted strings. They are equal, so the result is YES.

For the strings a = "hello" and b = "billion":

  1. Check the lengths of a and b. a is 5 and b is 7.
  2. Since the lengths are different, the result is NO.

Solution Logic:

  1. Check if the lengths of the two strings are the same. If not, they cannot be anagrams.
  2. Sort both strings and compare them. If they are equal, the strings are anagrams.

Time Complexity

  • The sorting-based approach has a time complexity of O(nlogn)O(n \log n), where n is the length of the strings.

Space Complexity

  • The auxiliary space complexity is O(1)O(1) for constant extra space.

References